#coding=utf-8
import os
import random
import socket
import signal
import time
import commands


systemNetWork = True#系统网络状态正常

def systemNetWorkSet(status):
    global systemNetWork
    systemNetWork = status

def systemNetWorkGet():
    global systemNetWork

    print systemNetWork
    return systemNetWork

def handler(signum, frame):
    raise AssertionError

pingaddr = ["www.baidu.com",
            "www.qq.com",
            "www.1688.com",
            "www.taobao.com"]
errNum = 0
#是否为AP配置文件
def isAPconfigFile():
    if os.path.isfile('/etc/network/interfaces') == False:#没有网络配置文件
        os.system('cp /home/fa/work/SmartCount/interfaces_wifi /etc/network/interfaces')#直接配置启动热点
        return True
    else:#有网络配置文件
        result = commands.getstatusoutput("cat /etc/network/interfaces | grep static -o")
        output = result[1]
        if output == 'static':#当前配置为热点配置
            return True
    return False

def systemNetStatusProcess():
    global  errNum
    run = 3
    result = -1
    while run:
        run -= 1
        ranPingAddr = random.choice(pingaddr)
        #print ranPingAddr
        pingShell = 'ping '+str(ranPingAddr)+' -c 1 >>/dev/null'
        print pingShell,errNum,'run=',run
        #if errNum < 4:
        #    print pingShell
        result = os.system(pingShell)
        if result == 0:
            break
        else:
            time.sleep(0.001)

    if result != 0:#网络断开
        errNum += 1
        print 'ping result:',result,errNum
        if errNum > 2 and errNum < 4:#重连路由器
            print 'relink WIFI'
            if isAPconfigFile() == False:#系统不是AP配置模式
                systemNetWorkSet(False)
                os.system('/etc/init.d/networking restart')
                os.system("killall udhcpc;udhcpc -i wlan1 -n")

        elif errNum == 4:#网络断开时间过长，启动AP模式
            print 'Start AP mode'
            if isAPconfigFile() == False:#系统不是AP配置模式
                os.system("cp /etc/network/interfaces /home/fa/work/SmartCount/interfaces")#保存原来的配置文件
            print 'Start AP mode'
            systemNetWorkSet(False)
            os.system("cp /home/fa/work/SmartCount/interfaces_wifi /etc/network/interfaces")#WIFI热点配置
            os.system("sync")
            #os.system("systemctl daemon-reload")
            #time.sleep(2)

            os.system("/etc/init.d/dnsmasq stop")#启动DNS服务
            os.system("/etc/init.d/hostapd stop")#启动热点
            time.sleep(2)
            os.system("killall hostapd")
            os.system("killall dnsmasq")
            os.system("/etc/init.d/hostapd restart")#启动热点
            time.sleep(7)
            os.system("/etc/init.d/dnsmasq restart")#启动DNS服务
            time.sleep(5)
            os.system("/etc/init.d/networking stop")
            time.sleep(5)
            os.system("/etc/init.d/networking start")
            time.sleep(10)
            os.system("ifconfig wlan1 192.168.10.1")
        elif errNum == 5:
            os.system("/etc/init.d/hostapd restart")#启动热点
        elif errNum >= 3600:#热点时间开启过长
            os.system("killall hostapd")
            os.system("killall dnsmasq")
            os.system("cp /home/fa/work/SmartCount/interfaces /etc/network/interfaces")
            os.system('/etc/init.d/networking restart')
            os.system("killall udhcpc;udhcpc -i wlan1 -n")
            errNum = 1
    else:
        errNum = 0
        systemNetWorkSet(True)
    return result

def configWifiConfig():
    port = 8081
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
    # 从给定的端口，从任何发送者，接收UDP数据报
    server.bind(("", port))
    print 'waiting on port:', port
    while True:
        data, addr = server.recvfrom(1024*4)

        print 'reciveed:', data, "from", addr

